<template>
  <page-wrap :loading="pageloading">
    <div class="save-container">
      <div class="save-card normal">
        <div class="save-cell">
          <div class="save-cell-label">
            <div class="save-cell-label__title">存酒桌号：</div>
          </div>
          <div class="save-cell-value">
            <div :class="[
              'save-cell-value__table',
              tableNumber ? 'cm-orange' : 'cm-gray']" @click="tableSelectShow = true">
              {{ tableNumber ? tableNumber : '选择桌位' }}
            </div>
          </div>
          <div class="save-cell-control">
            <van-image class="save-cell-control__icon" :src="i_cashier_scan" @click="getCameras" />
          </div>
          <div v-show="scanning" class="container">
            <div id="reader"></div>
          </div>
        </div>
      </div>
      <div class="save-card main">
        <div class="save-cell">
          <div class="save-cell-label">
            <div class="save-cell-label__label">会员手机号</div>
          </div>
          <div class="save-cell-value">
            <input v-model="postForm.mobile" type="number" class="save-cell-value__input" autocomplete="off"
              placeholder="请输入手机号" />
          </div>
          <div class="save-cell-control">
            <!-- <div class="save-cell-control__btn" @click="onDetect">检测</div> -->
          </div>
        </div>
        <!-- 开启状态的 -->
        <div class="wineChoose" v-if="GetconfigStaus">
          <div class="wineChoose-upper" @click="onOpen">
            <div class="wineChoose-title">酒水选择</div>
            <div class="wineChoose-right">
              <div class="wineChoose-value">请添加</div>
              <div class="wineChoose-icon"></div>
            </div>
          </div>
          <div class="wineChoose-below" v-show="addInfo">
            <div class="wineChoose-below-item" v-for="(item, index) in addInfo" :key="index"
              :class="{ active: winelist === index }" @click="reskopen(index)">
              <div class="below-item-header">
                <div class="below-item-left">
                  {{ item.Name }}
                </div>
                <div class="below-item-right">
                  <!-- {{  }} -->
                  <div class="below-item-num">×{{ item.total }}</div>

                  <img :src="minus" class="below-item-img" @click.stop="delreskItem(index)" />
                </div>
              </div>
              <div class="below-item-main" v-show="winelistShow === index && isShow">
                <ul class="below-main-ul">
                  <li class="below-main-li" v-for="(item1, index1) in item.children" :key="index1">
                    <div class="main-li-bottle" :class="{ active: item1.type === '2' }">
                      {{ item1.type === '1' ? '整瓶' : '非整瓶' }}
                    </div>
                    <div class="main-li-right">
                      <z-stepper :disabletype="2" :min="0" :default-value="item1.num" :max="getreskMaxValue(item1.type)" theme="square"
                        :step="item1.type == 1 ? 1 : 0.1" :class="{ nodel: index1 <= 1 }"
                        @change="onreskChange(index, index1, $event)" @click.stop=""></z-stepper>
                      <div v-if="index1 >= 2" @click.stop="onreskDel(item, index1)" class="main-li-del">
                        删除
                      </div>
                    </div>
                  </li>
                </ul>
                <div class="below-item-footer" v-if="item.StoreType === '2' || !item.StoreType">
                  <img :src="plus" class="item-footer-img" />
                  <div class="item-footer-title" @click.stop="onreskAddWine(item)">
                    添加一行非整瓶
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 关闭状态的 -->
        <div class="save-wine" v-else>
          <div class="save-wine-header">
            <div class="save-wine__title">酒水选择</div>
            <div class="save-wine__subtitle">请选择</div>
          </div>
          <div class="save-wine-main">
            <ul class="save-wine-list">
              <li class="save-wine-item" :class="{ active: wineShow === k }" v-for="(v, k) in wineList" :key="k"
                @click="showWine(k)">
                <div class="save-wine__header">
                  <div class="save-wine__name">{{ v.GoodsName }}</div>
                  <div class="save-wine__number">x{{ v.total }}</div>
                </div>
                <div class="save-wine-panel" v-show="wineShow === k && isShow">
                  <div class="save-wine-panel__item" v-for="(cv, ci) in v.children" :key="cv.id">
                    <div class="save-wine-panel__volume whole">
                      {{ cv.type == 1 ? '整瓶' : '非整瓶' }}
                    </div>
                    <div class="save-wine-panel__number">
                      <z-stepper :disabletype="2" button-size="32px" v-model="cv.num" :min="0"
                        :disabled="v.OrderQty < 1 && cv.type == '1'" :max="getMaxValue(cv.type, v.OrderQty)"
                        :default-value="cv.type == 1 ? 1 : 0.1" :disable-plus="cv.isCanPlus" theme="square"
                        :step="cv.type == 1 ? 1 : 0.1" @change="onChange(k, ci, $event)" @click.stop=""></z-stepper>
                    </div>
                    <div class="save-wine-panel__del">
                      <div v-if="ci > 1" @click.stop="onDel(v, k, ci)">
                        删除
                      </div>
                    </div>
                  </div>
                </div>
                <div class="save-wine-add" v-if="v.StoreType === '2'" v-show="wineShow === k && isShow">
                  <van-image class="save-wine-add__icon" :src="v_image_add" alt="SVG Icon" />
                  <div class="save-wine-add__text" @click.stop="onAdd(v)">
                    添加一行非整瓶
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>

        <!-- <div class="save-cell">
          <div class="save-cell-label">
            <div class="save-cell-label__label">寄存位置</div>
          </div>
          <div class="save-cell-control">
            <div
              :class="{
                'save-cell-control__select': true,
                checked: locationText != '请选择'
              }"
              @click="show = true"
            >
              {{ locationText }}
            </div>
          </div>
        </div>  -->
        <!-- </template> -->
      </div>
      <div v-if="GetconfigStaus">
        <div class="save-section" v-if="addInfo.length > 0">
          <div class="save-section-heading">存酒照片(酒水选择顺序对应)</div>
          <div class="save-card section">
            <zdupload v-model="fileList" :after-read="afterdrinkRead" :max="addInfo.length" />
          </div>
        </div>
      </div>
      <div v-else>
        <div class="save-section" v-if="wineList.length > 0">
          <div class="save-section-heading">存酒照片(酒水选择顺序对应)</div>
          <div class="save-card section">
            <!-- <z-uploader v-model="fileList" :after-read="afterRead" :max="wineList.length" /> -->
            <zdupload v-model="fileList" :after-read="afterdrinkRead" :max="wineList.length" />
          </div>
        </div>
      </div>

      <div class="save-section">
        <div class="save-section-heading">备注</div>
        <div class="save-section-remark">
          <van-field type="textarea" placeholder="请输入备注" v-model="postForm.remark" />
        </div>
      </div>
      <z-button-group top="30">
        <z-button v-if="GetconfigStaus" bold @click="onreskSubmit"  >确认</z-button>
        <z-button v-else bold @click="onSubmit"  >确认</z-button>
        <z-button plain top="10" @click="onCancle">取消</z-button>
      </z-button-group>
    </div>
  </page-wrap>

  <!-- 寄存位置 -->
  <z-action-sheet v-model:show="show" :actions="actions" @select="onSelect" />

  <!-- 选择桌台组件 -->
  <TableSelectSpe v-model:show="tableSelectShow" @close="onTableSelectClose" title="存酒" source="save" line="1"
    state="2,3">
  </TableSelectSpe>

  <!-- 扫描二维码弹窗 -->
  <!-- <QRScanner v-model:show="qrScannerShow" @success="onScanSuccess"></QRScanner>   -->


  <!-- 开通会员弹窗 -->
  <z-dialog v-model:show="openMemberShow" content="是否前往开通会员？" @confirm="onOpenMember"></z-dialog>

  <!-- 酒水选择弹窗 -->
  <z-popup v-model:show="addShow" closeable title="酒水选择">
    <div class="popup-wineChoose">
      <div class="popup-wineChoose-header">
        <z-search placeholder="请输入名称" @query="onQuery" v-model="postForm2.name" @update:model-value="onUpdateVal" />
      </div>
      <div class="popup-wineChoose-main">
        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="loadData"
          :immediate-check="false" offset="100">
          <div class="wineChoose-main-item" v-for="(item, index) in wineInfo" :key="index" @click="currentIndex = index"
            :class="{ active: currentIndex === index }">
            <div class="wineChoose-main-name">{{ item.Name }}</div>
          </div>
        </van-list>
      </div>
      <div class="popup-wineChoose-footer">
        <z-button @click="ondrinksAdd" style="width: 120px; margin: 0px auto">添加</z-button>
      </div>
    </div>
  </z-popup>
</template>

<script setup>
import { Html5Qrcode } from "html5-qrcode";
import { showToast } from 'vant'
import Api from '@/api'
import axios from 'axios'
import i_cashier_scan from '@/assets/images/open/i_cashier_scan.png'
import i_wine_1 from '@/assets/images/save/i_wine_1.png'
import v_image_add from '@/assets/svg/common/v_image_add.svg'
import triangle from '@/assets/svg/recycle/v_recycle-triangle.svg'
import minus from '@/assets/svg/recycle/v_recycle-minus.svg'
import plus from '@/assets/svg/recycle/v_recycle-plus.svg'
import useAppStore from '@/store/app'
import { onMounted } from 'vue'
import useSaveStore from '@/store/save'
const saveStore = useSaveStore()
import ls from '@/lib/ls'
import Compressor from "compressorjs";
import { validateMobile } from '@/lib/util.js'

// import _ from 'lodash'
const appStore = useAppStore()
const route = useRoute()
// 获取登录的服务员账户
const account = ref(appStore.user_info)
console.log(route.query)
const router = useRouter()
const tableNumber = ref(undefined)
const locationText = ref('吧台')
const qrScannerShow = ref(false)
const show = ref(false)
const actions = [
  { name: '吧台', storePosition: 1 },
  { name: '仓库', storePosition: 2 }
]
const fileList = ref([])
const wineList = ref([])
// 提交数据
const postForm = reactive({
  consumeCode: '',
  roomCode: '',
  // mobile: undefined,
  mobile: '',
  storePosition: 1,
  remark: '',
  images: '',
  goods: [],
  itemCode: '',
  userName: account.value.userName
})

const pageloading = ref(false)
const scanning = ref(false);
const cameraId = ref("");
const devicesInfo = ref("");
const html5QrCode = ref(null);
const getCameras = () => {
  nextTick(() => {
    scanning.value = true;
  });
  Html5Qrcode.getCameras()
    .then((devices) => {
      console.log("摄像头信息", devices);
      showToast("开启摄像头中，请稍等");
      if (devices && devices.length) {
        // 如果有2个摄像头，1为前置的
        if (devices.length > 1) {
          cameraId.value = devices[1].id;
        } else {
          cameraId.value = devices[0].id;
        }
        devicesInfo.value = devices;
        // start开始扫描
        start();
      }
    })
    .catch((err) => {
      // handle err
      console.log("获取设备信息失败", err); // 获取设备信息失败
      showToast("获取设备信息失败");
    });
};
const start = () => {
  html5QrCode.value = new Html5Qrcode("reader");
  console.log("html5QrCode", html5QrCode);

  html5QrCode.value
    .start(
      cameraId.value,
      {
        fps: 1, // 设置每秒多少帧
        qrbox: { width: 250, height: 250 }, // 设置取景范围
      },
      (decodedText, decodedResult) => {
        console.log("扫描的结果", decodedText, decodedResult);
        showToast("扫描的结果", decodedText, decodedResult);
        // result.value = decodedText
        scanning.value = false;
        // let inputElement = document.getElementById("inputId");
        // inputElement.value = decodedText;
        // onSubmit();
        const match2 = decodedText.match(/[?&]code=([^&]+)/);
        const match3 = decodedText.match(/[?&]name=([^&]+)/);
        let obj = {
          roomCode: match2 ? match2[1] : null,
          roomName: match3 ? match3[1] : null,
        }
        onTableSelectClose('', obj)
        if (decodedText) {
          stop();
        }
      },
      (errorMessage) => {
        // showToast('暂无扫描结果')
        console.log("暂无扫描结果", errorMessage);
      }
    )
    .catch((err) => {
      scanning.value = false;
      console.log(`Unable to start scanning, error: ${err}`);
    });
};
const stop = () => {
  if (!html5QrCode.value) return;
  html5QrCode.value
    .stop()
    .then((ignore) => {
      // QR Code scanning is stopped.
      console.log("QR Code scanning stopped.", ignore);
      // showToast('QR Code scanning stopped.')
    })
    .catch((err) => {
      // Stop failed, handle it.
      console.log("Unable to stop scanning.", err);
      showToast("Unable to stop scanning.");
    });
};


// 如果仓库中有数据，就赋值并显示
onMounted(() => {
  if (saveStore.wineList.length > 0) {
    console.log(saveStore.wineList)
    wineList.value = saveStore.wineList // 酒水信息
    tableNumber.value = saveStore.tableNumber // 存酒桌号
    postForm.mobile = saveStore.mobile // 手机号
    fileList.value = saveStore.fileList // 照片
    postForm.remark = saveStore.remark // 备注
    postForm.roomCode = saveStore.roomCode // 桌台号
  }
  // 修改寄存
  if (route.query.redirect == '/onwine') {
    Api.Common.AppObjProcess.Do({
      functionName: 'GetWineStoreDetail',
      contentData: { itemCode: route.query.itemCode }
    }).then(res => {
      console.log(res);
      wineList.value = mergeRecordsByGoodsCode([res.goods])
      console.log(wineList.value);
      postForm.mobile = res.memberMobile
      tableNumber.value = res.roomName
      postForm.roomCode = res.roomCode
      postForm.consumeCode = res.consumeCode
      postForm.itemCode = route.query.itemCode
      if (res.attachment) {
        let newArr = res.attachment.split(',')
        postForm.images = res.attachment // 照片
        fileList.value = newArr.map(function (item) {
          return { url: import.meta.env.VITE_DOMAIN + item }
        })
      }

      postForm.remark = res.remark
    })
  }
})
onUnmounted(() => {
  stop();
});
async function onInit(promise) {
  let errorString = ''
  try {
    const { capabilities } = await promise;
    const TORCH_IS_SUPPORTED = !!capabilities.torch;
    await promise;
  } catch (error) {
    if (error.name === 'NotAllowedError') {
      errorString = 'ERROR: 您需要授予相机访问权限';
    } else if (error.name === 'NotFoundError') {
      errorString = 'ERROR: 这个设备上没有摄像头';
    } else if (error.name === 'NotSupportedError') {
      errorString = 'ERROR: 所需的安全上下文(HTTPS、本地主机)';
    } else if (error.name === 'NotReadableError') {
      errorString = 'ERROR: 相机被占用';
    } else if (error.name === 'OverconstrainedError') {
      errorString = 'ERROR: 安装摄像头不合适';
    } else if (error.name === 'StreamApiNotSupportedError') {
      errorString = 'ERROR: 此浏览器不支持流API';
    }
    showToast(errorString)
  }
}

function mergeRecordsByGoodsCode(records) {
  const mergedRecords = {}

  records.forEach(record => {
    const goodsCode = record.goodsCode

    if (!mergedRecords[goodsCode]) {
      mergedRecords[goodsCode] = {
        GoodsCode: goodsCode,
        GoodsName: record.goodsName,
        // OrderQty: record.orderQty,
        OrderQty: record.storeQty,
        StoreType: record.storeType,
        UomCode: record.uomCode,
        UomName: record.uomName,
        children: [],
        total: parseFloat(record.storeQty)
      }
    } else {
      mergedRecords[goodsCode].total += parseFloat(record.storeQty)
    }

    const type = parseFloat(record.storeQty) >= 1 ? '1' : '2'

    let isCanPlus = false
    mergedRecords[goodsCode].children.push({
      type,
      num: parseFloat(record.storeQty),

      isCanPlus
    })
    if (mergedRecords[goodsCode].total > parseFloat(record.orderQty) - 1) {
      mergedRecords[goodsCode].children[0].isCanPlus = true
    }
  })

  return Object.values(mergedRecords)
}

// 选择寄存位置
const onSelect = item => {
  // 默认情况下点击选项时不会自动收起
  // 可以通过 close-on-click-action 属性开启自动收起
  locationText.value = item.name
  postForm.storePosition = item.storePosition
  show.value = false
}

// 选择桌台
const tableSelectShow = ref(false)
const onTableSelectClose = (type, args) => {
  tableSelectShow.value = false
  if (type == 'back') return
  const { roomName, roomCode } = args

  if (roomName) {
    tableNumber.value = args.roomName
    postForm.roomCode = args.roomCode
    saveStore.roomCode = args.roomCode // 存到仓库
  }
  const getRoomConsumeList = Api.Common.AppObjProcess.Do({
    functionName: 'getRoomConsumeList',
    contentData: postForm
  }).then(res => {
    let nowList = res.result
    nowList = nowList.filter(obj => obj.StoreType !== '0') // 过滤掉StoreType为0的（不可回收）
    nowList.forEach(obj => {
      console.log(obj);

      if (obj.StoreType === '2') {
        obj.children = [
          {
            type: '1',
            num: 0,
            isCanPlus: obj.OrderQty <= 0 ? true : false
          },
          {
            type: '2',
            num: 0,
            isCanPlus: obj.OrderQty <= 0 ? true : false
          }
        ]

      } else if (obj.StoreType === '1') {
        obj.children = [
          {
            type: '1',
            num: 0,
            isCanPlus: obj.OrderQty <= 0 ? true : false
          }
        ]
      } else if (obj.StoreType === '0') {
        showToast('该商品不可回收')
        return
      } else {
        obj.children = [
          {
            type: '1',
            num: 0,
            isCanPlus: false
          },
          {
            type: '2',
            num: 0,
            isCanPlus: false
          }
        ]
      }
      obj.total = 0
    })
    wineList.value = [] // 清空，防止重复添加
    Array.prototype.push.apply(wineList.value, nowList)
    console.log(wineList.value)
  })
}
// 添加非整瓶
const onAdd = v => {
  console.log(v)
  if (v.children.length > v.OrderQty) {
    showToast('存酒瓶数不能超过购买数量')
    return
  }
  if (v.children[1].isCanPlus === true) {
    v.children.push({
      type: '2',
      num: 0,
      isCanPlus: true
    })
  } else {
    v.children.push({
      type: '2',
      num: 0,
      isCanPlus: false
    })
  }
}
// 删除
const onDel = (v, k, ci) => {
  v.children.splice(ci, 1)
  wineList.value[k].children = wineList.value[k].children.map((obj, index) => {
    if (index === 0) {
      return obj // 跳过第一个元素
    }
    return { ...obj, isCanPlus: false }
  })
}
// 上传照片
const afterRead = async files => {
  const resp = await Api.Common.UploadPosWine.FileDo(files)
  console.log(resp);
  const urlPaths = resp.urlPath.split(',')
  console.log(urlPaths);
  const fileNames = resp.fileName.split(',')
  const transData = urlPaths.map((urlPath, index) => ({
    url: urlPath,
    name: fileNames[index]
  }))
  console.log(transData);
  for (const fileItem of unref(fileList)) {
    for (const transItem of transData) {
      if (!fileItem.url) {
        fileItem.url = transItem.url
      }
    }
  }
}

const ALLList = ref([]) // 转化用数组
// 保存按钮的权限
const btnFlag = ref(true)
const subFlag = ref(false) // 确认按钮开关
// --------------------------------------------------保存-------------------------------------------
const onSubmit = async() => {
  pageloading.value = true
  if(await onDetect()){ 
    pageloading.value = false
    return
  } 
  
  ALLList.value = [] // 清空，防止影响后续
  let objAll = {
    goodsCode: '',
    goodsName: '',
    uomCode: '',
    uomName: '',
    storeQty: '',
    isCanPlus: ''
  } // 转化用对象

  let wineNum = 0

  console.log(wineList.value, 'wineList.value')
  // 遍历数组，按需求生成新数组
  wineList.value.forEach(item => {
    if (item.children) {
      item.children.forEach((i, k) => {
        objAll = {} // 清空，防止影响后续
        objAll.goodsCode = item.GoodsCode
        objAll.goodsName = item.GoodsName
        objAll.uomCode = item.UomCode
        objAll.uomName = item.UomName
        objAll.isCanPlus = i.isCanPlus
        // objAll.images = urlConcatenated
        wineNum += i.num
        objAll.storeQty = i.num
        ALLList.value.push(objAll)
      })
    }
  })

  console.log(wineNum, 'wineNum')
  if (wineNum == 0) {
    showToast('酒水数量为零')
    pageloading.value = false
    return
  }
  
  // 过滤数量0 不需要上传
  const tempwineList = wineList.value.filter(item => item.total !== 0);
  console.log(tempwineList, 'tempwineList')
  
   if(waiterStoreStatus.value) {
      if (fileList.value.length < tempwineList.length) {
      showToast('存酒照片和酒水种类数量需要一致')
      pageloading.value = false
      return
    }
   }
 
  
  pageloading.value = true

  ALLList.value = ALLList.value.filter(obj => obj.storeQty !== 0)
  console.log(ALLList.value, 'ALLList.value')


  let imgList = fileList.value.map(item => item.url);
  console.log(imgList, 'imgList')

  const updatedGoodsList = ALLList.value.map((v, k) => {
    if (imgList.length > 0) {
      v.attachment = imgList[k]
    } else {
      v.attachment = ""
    }
    return v; // 返回更新后的对象
  });

  // 未上传置空
  updatedGoodsList.map(item=> {
      if(!item.attachment) {
        item.attachment = ''
      }
  })

  // 改成后端要的json格式
  ALLList.value = JSON.stringify(updatedGoodsList)
  postForm.goods = ALLList.value
  console.log(postForm, 'postForm');
  // return
  if (route.query.redirect == '/onwine') {
    // 更新存酒
    console.log(postForm);
    Api.Common.AppObjProcess.Do({
      functionName: 'UpdateWineStoreInfo',
      contentData: postForm
    }).then(res => {
      showToast('保存成功')
      // 清空仓库内容
      saveStore.wineList = [] // 酒水信息
      saveStore.tableNumber = '' // 存酒桌号
      saveStore.mobile = '' // 手机号
      saveStore.fileList = [] // 照片
      saveStore.remark = '' // 备注
      saveStore.roomCode = '' // 桌台号
      router.back()
      subFlag.value = false
    }).catch(err => {
      subFlag.value = false
    })
  } else {
    // 存酒
    Api.Common.AppObjProcess.Do({
      functionName: 'wineStore',
      contentData: postForm
    }).then(res => {
      showToast('保存成功')
      // 清空仓库内容
      saveStore.wineList = [] // 酒水信息
      saveStore.tableNumber = '' // 存酒桌号
      saveStore.mobile = '' // 手机号
      saveStore.fileList = [] // 照片
      saveStore.remark = '' // 备注
      saveStore.roomCode = '' // 桌台号
      router.back()
      pageloading.value = false
      subFlag.value = false
    }).catch(err => {
      subFlag.value = false
      pageloading.value = false
    })
  }

}

const onSubmitFlag = ref(false)
let objAll = {
  goodsCode: '',
  goodsName: '',
  uomCode: '',
  uomName: '',
  storeQty: ''
} // 转化用对象
const onreskSubmit = async() => { 
  pageloading.value = true
   if(await onDetect()){ 
    pageloading.value = false
    return
  } 
  ALLList.value = []
  // 遍历数组，按需求生成新数组
  if (addInfo.value.length === 0) {
    showToast('请选择酒水')
    pageloading.value = false
    return
  }

  if (addInfo.value.some(item => item.total === '0.0')) {
    showToast('酒水数量不能为零')
    pageloading.value = false
    return
  }
  
  if(waiterStoreStatus.value) {
    if (GetconfigStaus.value) {
    if (fileList.value.length < addInfo.value.length) {
      showToast('存酒照片和酒水种类数量需要一致')
      pageloading.value = false
      return
    }
  }
  }


  // if (onSubmitFlag.value) {
  //   showToast('提交中，请稍等')
  //   return
  // }
  pageloading.value = true
  onSubmitFlag.value = true

  addInfo.value.forEach(item => {
    if (item.children) {
      item.children.forEach(i => {
        objAll = {} // 清空，防止影响后续
        objAll.goodsCode = item.Code
        objAll.goodsName = item.Name
        objAll.uomCode = item.UomCode
        objAll.uomName = item.UomName
        objAll.storeQty = i.num
        ALLList.value.push(objAll)
      })
    }
  })

  //图片数据处理
  if (fileList.value.length > 0) {
    let imgList = fileList.value.map(item => item.url);
    console.log(imgList, 'imgList')
    console.log(CodeList.value, 'CodeList')

    // 使用 map 组合两个数组
    const combinedList = CodeList.value.map((goodsCode, index) => {
      return {
        goodsCode: goodsCode,
        url: imgList[index] // 根据索引配对图片 URL
      };
    });

    console.log(combinedList, 'casc');


    // 创建一个根据 goodsCode 和 recoveryQty 的映射
    const imgMap = combinedList.reduce((map, item) => {
      if (!map[item.goodsCode]) {
        map[item.goodsCode] = [];
      }
      map[item.goodsCode].push(item.url); // 将图片 URL 按照 goodsCode 分组
      return map;
    }, {});

    console.log(imgMap, 'imgMap')

    // 更新 ALLList.value attachment 字段
    const updatedGoodsList = ALLList.value.map(good => {
      // 获取对应 goodsCode 的图片数组
      const goodsImages = imgMap[good.goodsCode] || [];
      // 为每个商品添加 attachment 字段
      return {
        ...good,  // 保留其他字段
        attachment: goodsImages[0] || ""  // 如果找到图片，则添加，否则为空字符串
      };
    });

    ALLList.value = updatedGoodsList
  } else {
    ALLList.value.map(item => {
      item.attachment = ""
    })
  }


  ALLList.value = JSON.stringify(ALLList.value)

  let params = {
    roomCode: postForm.roomCode, // 存酒桌号
    mobile: postForm.mobile, // 手机号
    remark: postForm.remark,// 备注
    goods: ALLList.value
  }
  console.log(params, 'params-----------')
  const WineRecovery = Api.Common.AppObjProcess.Do({
    functionName: 'wineStore',
    contentData: params
  }).then(res => {
    showToast('存酒成功')
    pageloading.value = false
    router.push({
      path: `/`
    })
    onSubmitFlag.value = false
  }).catch(err => {
    onSubmitFlag.value = false
    pageloading.value = false
  })
}

const onCancle = () => {
  router.back()
  // 清空仓库内容
  saveStore.wineList = [] // 酒水信息
  saveStore.tableNumber = '' // 存酒桌号
  saveStore.mobile = '' // 手机号
  saveStore.fileList = [] // 照片
  saveStore.remark = '' // 备注
  saveStore.roomCode = '' // 桌台号
}
// 检测手机号
const openMemberShow = ref(false)
const onDetect = async() => {
  if (!postForm.mobile) {
    showToast('请输入手机号')
    return true
  }
  const checkMemberInfo = await Api.Common.AppObjProcess.Do({ functionName: 'checkMemberInfo', contentData: postForm }).then(res => {
    // btnFlag.value = false 
    // showToast('检测成功') 
    return false
  }).catch(err => {
    // btnFlag.value = true
    
  if(['0024', '0025'].includes(ls.get('ORG_CODE')) ) {
  //无会员卡-直接开通会员
  if(!validateMobile(postForm.mobile)) return
  const openCard = Api.Common.AppObjProcess.Do({"functionName": "MemberOpenCrad","contentData": {
    "orgCode": '00004',
    "mobiles": postForm.mobile,
  }})
  .then(res => {
    // showToast('开卡成功')
  })
  } else {
     openMemberShow.value = true
  }

    // 存到仓库中,以便返回时数据还在
    saveStore.wineList = wineList.value // 酒水信息
    saveStore.tableNumber = tableNumber.value // 存酒桌号
    saveStore.mobile = postForm.mobile // 手机号
    saveStore.fileList = fileList.value // 照片
    console.log(fileList.value)
    saveStore.remark = postForm.remark // 备注

    return true
  })
}
// 开通会员
const onOpenMember = () => {
  router.push({
    path: '/onmember/open',
    query: {
      redirect: '/save',
      mobile: postForm.mobile
    }
  })
}
// 监听电话号码的变化
watch(() => postForm.mobile,
  (newVal, oldVal) => {
    btnFlag.value = true
  }
)
const addInfo = ref([])

watch([() => postForm.mobile, () => addInfo.value],  // 监听多个值
  ([newMobile, newAddInfo], [oldMobile, oldAddInfo]) => {
    // 针对 addInfo.value 的处理逻辑
    if (newAddInfo) {
      newAddInfo.forEach(obj => {
        obj.total = obj.children.reduce((total, child) => total + child.num, 0).toFixed(1);
      });
    }
  },
  { deep: true } // 确保 deep 监听 addInfo.value 内部的变化
);


// 点击显示酒水全部内容
const wineShow = ref(0) // 切换到数组的第几个元素
const winelist = ref(0)
let isShow = ref(true)
const showWine = value => {
  if (wineShow.value !== value) {
    isShow.value = true
  } else {
    isShow.value = !isShow.value
  }
  wineShow.value = value
}






const onChange = (k, ci, value) => {
  console.log(wineList.value[k])
  postForm.consumeCode = wineList.value[k].ConsumeCode
  wineList.value[k].children[ci].num = value
  // 改变酒水的总数
  // wineList.value[k].total = wineList.value[k].children.reduce((total, child) => total + child.num, 0).toFixed(1)
  wineList.value[k].total = wineList.value[k].children.reduce((total, child) => {
      const num = Number(child.num);
      return isNaN(num) ? total : total + num;
  }, 0)
  .toFixed(1);

  if (Number((parseFloat(wineList.value[k].total) + 0.1).toFixed(1)) > wineList.value[k].OrderQty) {
    wineList.value[k].children = wineList.value[k].children.map(
      (obj, index) => {
        if (index === 0) {
          return obj // 跳过第一个元素
        }
        return { ...obj, isCanPlus: true }
      }
    )
  } else {
    wineList.value[k].children = wineList.value[k].children.map(
      (obj, index) => {
        if (index === 0) {
          return obj // 跳过第一个元素
        }
        return { ...obj, isCanPlus: false }
      }
    )
  }

  if (parseFloat(wineList.value[k].total) + 1 > wineList.value[k].OrderQty) {
    wineList.value[k].children[0].isCanPlus = true
  } else {
    wineList.value[k].children[0].isCanPlus = false
  }
}

// 非整瓶最大值为 0.9，整瓶没有最大值限制
const getMaxValue = (type, val) => {
  return type === '2' ? 0.9 : val
}



// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx以下代码手动选择酒水功能xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


const winelistShow = ref(0)
const reskopen = value => {
  winelist.value = value
  if (winelistShow.value !== value) {
    isShow.value = true
  } else {
    isShow.value = !isShow.value
  }
  winelistShow.value = value
}
// 非整瓶最大值为 0.9，整瓶没有最大值限制
const getreskMaxValue = type => {
  return type === '2' ? 0.9 : Infinity
}
// 步进器改变酒水数量
const onreskChange = (k, ci, value) => {
  addInfo.value[k].children[ci].num = value
}

// 删除添加的酒水
const delreskItem = item => {
  addInfo.value.splice(item, 1)
  fileList.value.splice(item, 1)
}
// 删除非整瓶
const onreskDel = (v, ci) => {
  v.children.splice(ci, 1)
}


const onreskAddWine = v => {
  v.children.push({
    type: '2',
    num: 0
  })
}


const CodeList = ref([])


const compressImage = async file => {
  if (!file) {
    return;
  }
  return new Promise((reslove, reject) => {
    // compressorjs 默认开启 checkOrientation 选项
    // 会将图片修正为正确方向
    new Compressor(file, {
      quality: 0.6, // 设置压缩质量，范围从 0 到 1，默认0.8
      maxWidth: 1000,
      maxHeight: 1000,
      convertSize: 1000000,
      checkOrientation: true, // 启用 EXIF 方向修正
      success(result) {
        const compressedImage = new File([result], result.name, { type: result.type });
        reslove(compressedImage);
      },
      error(err) {
        reject(err.message);
      },
    });
  });
}

// -----------------------------------上传照片----------------------------------------
const afterdrinkRead = async (files) => {

  // 如果是一次多张上传
  if (Array.isArray(files)) {
    files.forEach(async item => {
      item.file = await compressImage(item.file);
    });
  } else {
    // 单文件上传
    files.file = await compressImage(files.file);
  }

  // return
  const resp = await Api.Common.UploadPosWine.FileDo(files)
  console.log(resp);
  const urlPaths = resp.urlPath.split(',')
  console.log(urlPaths);
  const fileNames = resp.fileName.split(',')
  const transData = urlPaths.map((urlPath, index) => ({
    url: urlPath,
    name: fileNames[index]
  }))
  console.log(transData);
  for (const fileItem of unref(fileList)) {
    for (const transItem of transData) {
      if (!fileItem.url) {
        fileItem.url = transItem.url
      }
    }
  }
  console.log(fileList.value, 'transData2');
}


//----------------------------------------------加载---------------------------------------------------
//表单
const postForm2 = reactive({
  name: '',
  pageSize: 15,
  pageIndex: 1
})
const loading = ref(false)
const finished = ref(false)
const loadData = async function (refresh = false) {
  if (refresh === true) {
    finished.value = false
    postForm2.pageIndex = 1
    wineInfo.value = []
  }
  loading.value = true
  const resp = await Api.Common.AppObjProcess.Do({
    functionName: 'getWineListByName',
    contentData: postForm2
  })
  let nowList = resp.result

  if (refresh === true) {
    if (nowList.length !== postForm2.pageSize) {
      finished.value = true
    }
  }
  nowList = nowList.filter(obj => obj.StoreType !== '0') // 过滤掉StoreType为0的（不可回收）
  // 添加默认的整瓶和非整瓶数组 StoreType对应能不能回收非整瓶
  nowList.forEach(obj => {
    if (obj.StoreType === '2') {
      obj.children = [
        {
          type: '1',
          num: 0
        },
        {
          type: '2',
          num: 0
        }
      ]
    } else if (obj.StoreType === '1') {
      obj.children = [
        {
          type: '1',
          num: 0
        }
      ]
    } else if (obj.StoreType === '0') {
      // showToast('该商品不可回收')
      // return
    } else {
      obj.children = [
        {
          type: '1',
          num: 0
        },
        {
          type: '2',
          num: 0
        }
      ]
    }
    obj.total = 0
  })
  Array.prototype.push.apply(wineInfo.value, nowList)
  if (nowList.length > 0) {
    postForm2.pageIndex++
  } else {
    finished.value = true
  }
  loading.value = false
  // if (refresh===true) {
  //     initBs.value++
  // }
}



//----------------------------------------------酒水选择 添加弹窗------------------------------------------------

const wineInfo = ref([])
const currentIndex = ref(0) // 哪一个高亮显示
const addShow = ref(false)
const onOpen = () => {
  // 请添加弹窗
  postForm2.name = ''
  addShow.value = true
  loadData(true)
}

//----------------------------------------------请添加弹窗查询---------------------------------------------------
const onQuery = () => {
  loadData(true)
}
const searchTimer = ref(null)
const onUpdateVal = val => {
  clearTimeout(unref(searchTimer))
  searchTimer.value = setTimeout(() => {
    loadData(true)
  }, 500)
}

//----------------------------------------------请添加弹窗确认添加---------------------------------------------------
const ondrinksAdd = () => {
  if (!wineInfo.value[currentIndex.value]) {
    showToast('未选择酒水')
    return
  }
  if (
    addInfo.value.some(
      item => item.Code === wineInfo.value[currentIndex.value].Code
    )

  ) {
    showToast('该酒水已选择')
    return
  }
  CodeList.value.push(wineInfo.value[currentIndex.value].Code)
  addInfo.value.push(wineInfo.value[currentIndex.value])
  addShow.value = false
}


const GetconfigStaus = ref(null)
const waiterStoreStatus = ref(null) // 服务员端存酒图片限制
//获取酒水开关状态
const GetBaseConfig = () => {
  Api.Common.AppObjProcess.Do({ "functionName": "GetBaseConfigInfo", "contentData": { orgCode: ls.get('ORG_CODE') } }).then(res => {
    GetconfigStaus.value = res.isAutoWinStore
    waiterStoreStatus.value = res.waiterStoreWinePictureLimit
    console.log(res,'res')
  })
}

GetBaseConfig()
</script>

<style scoped lang="scss">
.container {
  width: 100vw;
  height: 100%;
  position: absolute;
  top: 50px;
  left: 0;
  z-index: 999;
}

.save-container {
  padding: 0 12px 35px;

  .save-card {
    background: #28282e;
    border-radius: 8px;
    padding: 12px;

    &.normal {
      margin-top: 10px;

      .save-cell {
        padding: 0;
      }
    }

    &.main {
      margin-top: 10px;
      padding: 0 12px 18px;

      .save-cell {
        padding: 13px 0;
        border-bottom: 1px solid #383840;
      }

      .save-wine {
        padding-top: 18px;
      }
    }

    &.section {
      margin-top: 20px;
    }

    .save-cell {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 18px 0;
      border-top: 1px solid #383840;

      &:first-child {
        border-top: 0;
      }

      &-label {
        &__title {
          font-size: 18px;
          font-family: PingFang SC;
          font-weight: bold;
          color: #ffffff;
          line-height: 18px;
        }

        &__label {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #cccccc;
          line-height: 16px;
        }
      }

      &-value {
        flex: 1;
        font-size: 0;

        &__table {
          font-size: 18px;
          font-family: PingFang SC;
          font-weight: 500;
          // color: #999999;
          line-height: 18px;
          display: inline-block;
          padding-right: 14px;
          position: relative;

          &:after {
            content: '';
            width: 6px;
            height: 100%;
            position: absolute;
            top: 0;
            right: 0;
            background-image: url('@/assets/svg/common/v_triangle_right_white.svg');
            background-repeat: no-repeat;
            background-size: 100% auto;
            background-position: center center;
          }
        }

        &__input {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #ffffff;
          line-height: 16px;
          display: block;
          width: 100%;
          padding-left: 20px;
        }
      }

      &-control {
        &__icon {
          display: block;
          width: 24px;
          height: 24px;
        }

        &__btn {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #ffffff;
          line-height: 16px;
          padding: 5px 10px;
          background: #5c5c66;
          border-radius: 4px;
          cursor: pointer;
        }

        &__text {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #999999;
          line-height: 16px;
        }

        &__select {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #999999;
          line-height: 16px;
          padding-right: 17px;
          position: relative;
          cursor: pointer;

          &.checked {
            color: #ffffff;
          }

          &:after {
            content: '';
            width: 11px;
            height: 100%;
            position: absolute;
            top: 0;
            right: 0;
            background-image: url('@/assets/svg/common/v_triangle_bottom_white.svg');
            background-repeat: no-repeat;
            background-size: 100% auto;
            background-position: center center;
          }
        }
      }
    }

    .save-wine {
      &-header {
        display: flex;
        justify-content: space-between;
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #999999;
        line-height: 16px;
      }

      &__title {}

      &__subtitle {}

      &-main {}

      &-list {
        padding-top: 2px;
      }

      &-item {
        margin-top: 10px;
        padding: 13px 12px;
        background: #383840;
        border-radius: 8px;

        &.active {
          border: 1px solid #ffdd99;
        }
      }

      &__header {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 500;
        line-height: 14px;
      }

      &__name {
        color: #ffffff;
      }

      &__number {
        color: #cccccc;
      }

      &-panel {
        padding: 0 13px;

        &__item {
          padding-top: 12px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        &__volume {
          width: 40px;
          background: #454d41;
          border-radius: 2px;
          padding: 3px 0;
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 500;
          line-height: 12px;
          text-align: center;

          &.whole {
            background: #454d41;
            color: #8ae65c;
          }

          &.half {
            background: #494d41;
            color: #b8e65c;
          }
        }

        &__number {
          flex: 1;
          display: flex;
          justify-content: flex-end;
        }

        &__del {
          width: 47px;
          text-align: right;
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #66ccff;
          line-height: 14px;
          cursor: pointer;
        }
      }

      &-add {
        display: flex;
        align-items: center;
        padding-top: 12px;
        cursor: pointer;

        &__icon {
          display: block;
          width: 16px;
          height: 16px;
        }

        &__text {
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #ffaa00;
          line-height: 12px;
          padding-left: 4px;
        }
      }
    }
  }

  .save-section {
    padding-top: 30px;

    &-heading {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #ffffff;
      line-height: 16px;
    }

    &-remark {
      padding-top: 20px;

      :deep(.van-cell) {
        background: #28282e;
        border-radius: 8px;
        padding: 7px 12px 12px 12px;
        height: 60px;

        .van-field__control {
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #ffffff;
          line-height: 24px;

          &::placeholder {
            color: #999999;
          }
        }
      }
    }
  }
}



/* 相关样式 */
.reader-box {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.reader-box .desc {
  position: fixed;
  bottom: 140px;
  font-family: PingFang SC, PingFang SC;
  font-weight: bold;
  font-size: 15px;
  color: #ffffff;
  margin-top: 16px;
}

.reader-box .van-button {
  position: absolute;
  bottom: 70px;
  width: 90%;
  border: 1px solid #fff;
}

.line {
  position: absolute;
  top: 180px;
  width: 100%;
  animation: radar-beam 2s infinite;
  animation-timing-function: cubic-bezier(0.53, 0, 0.43, 0.99);
  animation-delay: 1.4s;
  z-index: 9999;
  height: 130px;
  border-bottom: 1px solid #4b66d0;
  background: linear-gradient(to top, #4b66d0, transparent);
}

@keyframes radar-beam {
  0% {
    transform: translateY(-100%);
  }

  100% {
    transform: translateY(90%);
  }
}


.wineChoose {
  .wineChoose-upper {
    background: #28282e;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 18px 12px;

    .wineChoose-title {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #cccccc;
      line-height: 16px;
    }

    .wineChoose-right {
      display: flex;
      align-items: center;

      .wineChoose-value {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffaa00;
        line-height: 16px;
      }

      .wineChoose-icon {
        width: 16px;
        height: 16px;
        margin-left: 7px;
        background-image: url('@/assets/svg/recycle/v_recycle-plus.svg');
        background-repeat: no-repeat;
        background-size: 100% 100%;
      }
    }
  }

  .wineChoose-below {
    background: #28282e;
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
    padding: 2px 24px 2px;

    .wineChoose-below-item {
      // padding-bottom: 20px;
      padding: 13px 12px;
      background: #383840;
      border-radius: 8px;
      margin-bottom: 10px;

      &.active {
        border: 1px solid #ffdd99;
      }

      .below-item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .below-item-left {
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #ffffff;
          line-height: 14px;
        }

        .below-item-right {
          display: flex;

          .below-item-num {
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 500;
            color: #cccccc;
            line-height: 14px;
            margin-right: 12px;
          }

          .below-item-img {
            width: 16px;
            height: 16px;
          }
        }
      }

      .below-item-main {
        .below-main-ul {
          padding: 12px 38px 0 13px;

          .below-main-li {
            list-style: none;
            display: flex;
            align-items: center;
            justify-content: space-between;

            padding-bottom: 12px;

            .main-li-bottle {
              width: 40px;
              text-align: center;
              background: #454d41;
              border-radius: 2px;
              padding: 3px 0;
              font-size: 12px;
              font-family: PingFang SC;
              font-weight: 500;
              color: #8ae65c;
              line-height: 12px;

              &.active {
                background: #494d41;
                color: #b8e65c;
              }
            }

            .main-li-right {
              display: flex;
              align-items: center;

              .nodel {
                margin-right: 46px;
              }

              .main-li-del {
                margin-left: 19px;
                font-size: 14px;
                font-family: PingFang SC;
                font-weight: 500;
                color: #66ccff;
                line-height: 14px;
              }
            }
          }
        }
      }

      .below-item-footer {
        display: flex;
        align-items: center;
        padding-left: 12px;
        padding-bottom: 8px;

        .item-footer-img {
          width: 16px;
          height: 16px;
          margin-right: 4px;
        }

        .item-footer-title {
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #ffaa00;
          line-height: 12px;
        }
      }
    }
  }
}

.popup-wineChoose {
  .popup-wineChoose-header {
    background: #45454d;
    margin-top: 10px;
    position: sticky;
    left: 0;
    top: 0;
    width: 100%;
  }

  .popup-wineChoose-main {
    max-height: 400px;
    overflow-y: auto;
    margin: 0px 12px;
    min-width: 310px;
    padding: 10px 0;
    border-top: 1px solid #505059;

    .wineChoose-main-item {
      &.active {
        border: 1px solid #ffdd99;
        padding: 12px 12px;
      }

      background: #404047;
      border-radius: 8px;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 13px 12px;

      .wineChoose-main-name {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffffff;
        line-height: 16px;
      }
    }
  }

  .popup-wineChoose-footer {
    background: #45454d;
    // position: sticky;
    // left: 0;
    // bottom: 0;
    // width: 100%;
    padding: 20px 0;
  }
}
</style>
